package com.desktop.click.tool.listener;

import com.desktop.click.tool.frame.Add;
import com.desktop.click.tool.frame.Main;
import com.desktop.click.tool.util.MouseUtil;
import com.desktop.click.tool.util.RobotUtil;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/**
 * 全局键盘监听类
 */
public class KeyboardListener implements NativeKeyListener {

    private Main main;

    private Add add;

    public void setAdd(Add add) {
        this.add = add;
    }

    public void nativeKeyPressed(NativeKeyEvent e) {
//        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
        if (e.getKeyCode() == NativeKeyEvent.VC_E) {
//            System.out.println("x:" + MouseUtil.getMouseX());
//            System.out.println("y:" + MouseUtil.getMouseY());
            if (add != null) {
                add.setLocation();
            }
        }
        if (e.getKeyCode() == NativeKeyEvent.VC_S) {
            RobotUtil.stop();
//            System.out.println("停止机器人辅助");
        }
    }

    public void nativeKeyReleased(NativeKeyEvent e) {
//        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public void nativeKeyTyped(NativeKeyEvent e) {
//        System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
    }

    /**
     * 键盘监听开始
     *
     * @return void
     * @date 2023/2/10 14:46
     * @author glq
     */
    public void start() {
        try {
            //关闭日志
            LogManager.getLogManager().reset();
            Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
            logger.setLevel(Level.OFF);
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());

            System.exit(1);
        }
        GlobalScreen.addNativeKeyListener(this);
    }
}
